import { Controller } from 'egg';

interface tokenType {
  username: string;
  password: string;
  type: number;
}
interface resultType<T> {
  code: number;
  message: string;
  data: T
}
export default class TeacherController extends Controller {
  private validateToken():tokenType {
    const token:any = this.ctx.request.header.authorization;
    const decode:string = JSON.stringify(this.ctx.app.jwt.verify(token, this.app.config.jwt.secret));
    const decodeParse:tokenType = JSON.parse(decode);
    return decodeParse;
  }
  /**
   * 查询所有教师
   */
  public async queryTeacherAll() {
    const { ctx } = this;
    const decode:tokenType = this.validateToken();
    const result = await ctx.service.teacherService.queryTeacherAll(decode, ctx.query) as resultType<object>;
    ctx.body = result;
  }

  /**
   * 添加教师
   */
  public async addTeacher() {
    const { ctx } = this;
    ctx.validate({
      user_id: 'int',
      class_id: 'int',
      subject: 'string',
    }, ctx.request.body);
    const decode:tokenType = this.validateToken();
    const result = await ctx.service.teacherService.addTeacher(ctx.request.body, decode) as resultType<[]>;
    ctx.body = result;
  }


  /**
   * 删除教师
   */
  public async delTeacher() {
    const { ctx } = this;
    ctx.validate({ id: 'int' }, ctx.request.body);
    const decode:tokenType = this.validateToken();
    const result = await ctx.service.teacherService.delTeacher(ctx.request.body.id, decode) as resultType<[]>;
    ctx.body = result;
  }

  /**
   * 修改教师
   */
  public async updateTeacher() {
    const { ctx } = this;
    ctx.validate({ id: 'int', user_id: 'int', class_id: 'int', subject: 'string' }, ctx.request.body);
    const decode:tokenType = this.validateToken();
    const result = await ctx.service.teacherService.updateTeacher(ctx.request.body, decode) as resultType<[]>;
    ctx.body = result;
  }
}
